package com.auemall.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.auemall.constant.ApplicationConstant;
import com.auemall.service.PictureService;
import com.auemall.utils.IDUtils;
import com.auemall.vo.UploadFileAndPictureRespVO;


@Service
public class PictureServiceImpl implements PictureService {
	
	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	
	@Value("${FTP_PORT}")
	private Integer FTP_PORT;
	
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	
	@Value("${IMAGE_BASE_PATH}")
	private String IMAGE_BASE_PATH;
	
	@Value("${FILE_BASE_PATH}")
	private String FILE_BASE_PATH;

	@Override
	public Map<String,Object> uploadPicture(MultipartFile uploadFile) {
		Map<String,Object> resultMap = new HashMap<>();
		try {
			//生成一个新的文件名
			//取原始文件名
			String oldName = uploadFile.getOriginalFilename();
			//生成新文件名
			//UUID.randomUUID();
			String newName = IDUtils.genImageName();
			newName = newName + oldName.substring(oldName.lastIndexOf("."));
			//图片上传
			String imagePath = new DateTime().toString("/yyyy/MM/dd");
			
//			System.out.println("上传图片路径"+IMAGE_BASE_PATH+imagePath);
			
			FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), new File(IMAGE_BASE_PATH+imagePath,newName)); 
			
			/*boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, 
					FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
			//返回结果
			if(!result) {
				resultMap.put("error", 1);
				resultMap.put("message", "文件上传失败");
				return resultMap;
			}*/
			resultMap.put("error", 0);
			resultMap.put("url", IMAGE_BASE_PATH + imagePath + "/" + newName);
			return resultMap;
			
		} catch (Exception e) {
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
			return resultMap;
		}
	}

    @Override
    public void UploadFile(HttpServletRequest request,HttpServletResponse response) throws Exception {

        //判断是否是文件上传请求
       if(ServletFileUpload.isMultipartContent(request)){
           // 创建文件上传处理器
           ServletFileUpload upload = new ServletFileUpload();
           //限制单个上传文件的大小
           upload.setFileSizeMax(1024*1024*1000);     //1L<<24
           
           try {
               // 解析请求
               FileItemIterator iter = upload.getItemIterator(request);
              
               while (iter.hasNext()) {
                   
                   FileItemStream item = iter.next();
              
                  
                   
                   if (!item.isFormField()) {
                       
                       //是文件上传对象，获取上传文件的输入流
                       InputStream srcinInputStream = item.openStream();
                       /*对上传文件的输入流进行处理，跟本地的文件流处理方式相同*/
                       
                     //这里将上传得到的文件保存至 d:\\temp\\file 目录  
                       FileUtils.copyInputStreamToFile(srcinInputStream, new File("E:\\auelog\\",   
                              item.getName())); 
                   }
               }
               
               System.out.println("上传成功...........");
               
               request.setAttribute("message","upload success!");
               
//               request.getRequestDispatcher("index").forward(request, response);;
               
           } catch (FileUploadException e) {
               e.printStackTrace();
               System.out.println("上传文件过大");
           } catch (IOException e) {
               e.printStackTrace();
               System.out.println("文件读取出现问题");
           }
       }
       
        
    }

    @Override
    public UploadFileAndPictureRespVO uploadFileAndPicture(MultipartFile uploadFile) {
        UploadFileAndPictureRespVO respVO = new UploadFileAndPictureRespVO();
        try {
            //生成一个新的文件名
            //取原始文件名
            String oldName = uploadFile.getOriginalFilename();
            //生成新文件名
            //UUID.randomUUID();
            String newName = IDUtils.genImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //图片上传
            String imagePath = new DateTime().toString("/yyyy/MM/dd");
            
//            System.out.println("上传文件路径"+FILE_BASE_PATH+imagePath);
            //这里将上传得到的文件保存至 d:\\temp\\file 目录  
            FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), new File(FILE_BASE_PATH+imagePath,newName)); 
            
//            boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, 
//                    FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
//            System.out.println("aue上传成功...........");
            
            respVO.setUrl(imagePath + "/" + newName);
            respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
            respVO.setMsg("上传成功");
            
        } catch (Exception e) {
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("上传失败");
        }
        return respVO;
    }

}
